package cn.tb.ymcc.mq.consumer;

import cn.tb.ymcc.domain.PayOrder;
import cn.tb.ymcc.dto.PayDto;
import cn.tb.ymcc.service.IPayOrderService;
import cn.tb.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 课程订单生成支付单的消费者
 */
@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "service-order-producer",
        topic = "course-order-topic",
        selectorExpression = "course-order-tag"
)
public class CourseOrder2CoursePayConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IPayOrderService payOrderService;

    /**
     * 消费消息
     * 1.校验消息是否为空
     * 2.根据拿到的订单号，查询payOrder表，校验订单号对应的支付单是否已经存在
     *  2.1有，说明已经消费过了，直接签收
     *  2.2没有，第一次消费，保存支付单
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        AssertUtil.isNotNull(body,"消息体为空！");
        String bodyStr = new String(body, StandardCharsets.UTF_8);
        PayDto payDto = JSONObject.parseObject(bodyStr, PayDto.class);
        PayOrder payOrder = payOrderService.selectByOrderNo(payDto.getOrderNo());
        if(payOrder != null){
            log.info("支付单已经存在，不再消费消息，直接签收");
            return;
        }
        //没有，第一次消费，保存支付单
        payOrder = new PayOrder();
        BeanUtils.copyProperties(payDto,payOrder);
        payOrder.setCreateTime(new Date());
        //设置支付单状态为待支付
        payOrder.setPayStatus(PayOrder.STATE_WAIT_PAY);
        payOrderService.insert(payOrder);
    }
}
